package com.qq.sentinel.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.qq.sentinel.handler.UserBlockHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("api/user")
public class UserController {

    /**
     * 测试流控规则
     */
    @GetMapping("testFlow")
    @SentinelResource(value = "user-testFlow",
            blockHandlerClass = UserBlockHandler.class, //对应异常类
            blockHandler = "handleException", //只负责sentinel控制台配置违规
            fallback = "handleError",  //只负责业务异常
            fallbackClass = UserBlockHandler.class
    )
    public String testFlow() {
        Map<String, Object> result = Maps.newHashMap();
        result.put("code", 200);
        result.put("msg", "成功");
        return JSON.toJSONString(result);
    }


    /**
     * 测试降级规则
     */
    @GetMapping("testDegrade")
    @SentinelResource(value = "user-testDegrade",
            blockHandlerClass = UserBlockHandler.class, //对应异常类
            blockHandler = "handleException", //只负责sentinel控制台配置违规
            fallback = "handleError", //只负责业务异常
            fallbackClass = UserBlockHandler.class
    )
    public String testDegrade() {
        Map<String, Object> result = Maps.newHashMap();
        result.put("code", 200);
        result.put("msg", "成功");
        return JSON.toJSONString(result);
    }


}
